import { defineStore } from 'pinia'
import { userApi } from '@/api'
import { md5 } from 'js-md5'
import { error } from 'console'
const useStore = defineStore('storeId', {
  // arrow function recommended for full type inference
  state: () => ({
    // all these properties will have their type inferred automatically
    user: {
      username: '',
      checkId: '',
    
      requestId:  '',
    },
    token: uni.getStorageSync('token'),
    count: 0
  }),
  getters: {
    isEven: (state) => state.count % 2 === 0
  },
  actions: {
    synIncrease() {
      this.count += 1
    },
    async asyncIncrease() {
      await new Promise((resolve) => setTimeout(resolve, 1000))
      this.count += 1
    },
    setUserInput(checkId: string, requestId: string) {
      this.user.checkId = checkId
      this.user.requestId = requestId
      // 保存到 cookies
      uni.setStorageSync('checkId', checkId)
      uni.setStorageSync('requestId', requestId)
    },

    // 从 cookies 加载 checkId 和 requestId
    loadUserInput() {
      this.user.checkId = uni.getStorageSync('checkId') || ''
      this.user.requestId = uni.getStorageSync('requestId') || ''
    },
    async login(username: string, password: string) {
      return new Promise(async (resolve, reject) => {
        await userApi.login(username, md5(password)).then(res => {
          //  this.user.username = res.data.username
          uni.setStorageSync('token', res.data.token)
          uni.showToast({
            title: "登录成功",
            icon: "success",
          });
          setTimeout(() => {
            resolve(res.data)
            uni.reLaunch({ url: '/pages/index/index' });
          }, 1000)

        }).catch(error => {
          reject(error)
        })


      })


    },
    async getInfo() {
      await userApi.getinfo().then(res => {
        this.user.username = res.data.name
      })
    },
    loginOut() {
      uni.setStorageSync('token', '')
      this.user = null;
      uni.reLaunch({ url: '/pages/login/index' });
    }
  }
})

export default useStore
